package com.xcx.order.service.impl;

import com.bootdo.lgs.order.model.LgsOrder;
import com.bootdo.lgs.order.service.OrderService;
import com.bootdo.lgs.ordertrace.dao.OrderTraceMapper;
import com.bootdo.lgs.ordertrace.model.OrderTrace;
import com.bootdo.lgs.ordertrace.service.OrderTraceService;
import com.bootdo.oa.domain.NotifyDO;
import com.bootdo.oa.service.NotifyService;
import com.bootdo.system.domain.UserDO;
import com.google.common.collect.Maps;
import com.xcx.order.dao.XcxBindPhoneMapper;
import com.xcx.order.dao.XcxOrderMapper;
import com.xcx.order.model.SearchQuery;
import com.xcx.order.model.bind.XcxBind;
import com.xcx.order.model.XcxOrderQuery;
import com.xcx.order.model.bind.XcxBindPhone;
import com.xcx.order.service.XcxOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class XcxOrderServiceImpl implements XcxOrderService {

    @Autowired
    private XcxOrderMapper xcxOrderMapper;

    @Autowired
    private XcxBindPhoneMapper xcxBindPhoneMapper;

    @Autowired
    private OrderTraceMapper orderTraceMapper;

    @Resource
    private NotifyService notifyService;

    @Autowired
    private OrderService orderService;

    @Autowired
    OrderTraceService orderTraceService;

    @Override
    public Boolean isBindPhone(XcxBind condition) {
        condition.setPhoneNum(Optional.ofNullable(condition.getPhoneNum()).orElse("no_phone"));
        XcxBindPhone xcxBindPhone = xcxBindPhoneMapper.getBindPhone(condition);
        if (xcxBindPhone != null) {
            condition.setId(xcxBindPhone.getId());
            return true;
        }
        return false;
    }

    @Override
    public int addBindPhone(XcxBind condition) {
        return xcxBindPhoneMapper.addBindPhone(condition);
    }

    @Override
    public int updateBindPhone(XcxBind condition) {
        return xcxBindPhoneMapper.updateBindPhone(condition);
    }

    @Override
    public Boolean isCodePass(XcxBind condition) {
        condition.setPhoneNum(Optional.ofNullable(condition.getPhoneNum()).orElse("no_phone"));
        XcxBindPhone xcxBindPhone = xcxBindPhoneMapper.getBindPhone(condition);
        if (xcxBindPhone != null) {
            if (xcxBindPhone.getCode().equals(condition.getInputCode()) && xcxBindPhone.getExpireTime().compareTo(new Date()) > 0)
                return true;
        }
        return false;
    }

    @Override
    public Boolean isChangePhone(XcxBind condition) {
        condition.setPhoneNum(Optional.ofNullable(condition.getPhoneNum()).orElse("no_phone"));
        XcxBindPhone xcxBindPhone = xcxBindPhoneMapper.getBindPhone(condition);
        if (xcxBindPhone != null) {
            if (xcxBindPhone.getPhoneType() != null && xcxBindPhone.getPhoneType().equals(condition.getPhoneType()))
                return false;
        }
        return true;
    }

    @Override
    public String getUserRole(XcxOrderQuery condition) {
        if (condition.getPhoneNum() == null || "".equals(condition.getPhoneNum()))
            return "kh";
        return Optional.ofNullable(xcxOrderMapper.getUserRole(condition.getPhoneNum())).orElse("kh");
    }

    @Override
    public void initQueryCondition(int status, XcxOrderQuery condition) {
        condition.setStatus(status);
        condition.setUserRole(Optional.ofNullable(condition.getUserRole()).orElse("kh"));
        if ("wl".equals(condition.getUserRole()))
            condition.setLgsCompanyCd(Optional.ofNullable(xcxOrderMapper.getCompanyCdByPhoneNum(Optional.ofNullable(condition.getPhoneNum()).orElse("no_phone"))).orElse("no_company"));
        condition.setLimit(Optional.ofNullable(condition.getPageSize()).orElse(null));
        if (condition.getPageNum() != null && condition.getPageSize() != null)
            condition.setOffset((condition.getPageNum()) * condition.getPageSize());
    }

    @Override
    public int countList(XcxOrderQuery condition) {
        return xcxOrderMapper.countList(condition);
    }

    @Override
    public List getList(XcxOrderQuery condition) {
        return xcxOrderMapper.getList(condition);
    }

    @Override
    public LgsOrder getDetail(XcxOrderQuery condition) {
        return xcxOrderMapper.getDetail(condition);
    }

    @Override
    public List getOrderTraceList(XcxOrderQuery condition) {
        List<OrderTrace> list = orderTraceMapper.getList(condition.getOrderId());
        List<OrderTrace> newList = new ArrayList<>();
        if (list != null && list.size() > 0)
            newList = list.stream().sorted(Comparator.comparing(OrderTrace::getFtime).reversed()).collect(Collectors.toList());
        return newList;
    }

    @Override
    public void sendUnpackNotice(Long orderId) {
        //获取需要发送订单的信息详情
        XcxOrderQuery condition = new XcxOrderQuery();
        condition.setOrderId(orderId);
        LgsOrder lgsOrder = getDetail(condition);
        if (lgsOrder == null)
            return;
        //发送通知 给需要提醒的人员
        NotifyDO notifyDO = new NotifyDO();
        notifyDO.setType("4");
        notifyDO.setTitle("【协助拆箱提醒】");
        notifyDO.setContent("物流运单号【" + lgsOrder.getLgs_track_number() + "】的【" + lgsOrder.getCustomer_name() + "】，选择需要协助拆箱。");
        notifyService.notifyOrderTrace(lgsOrder.getId(), lgsOrder.getLgs_company_cd(), notifyDO);
    }

    @Override
    public void initSearchQuery(SearchQuery condition) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        //过去一年
        c.setTime(new Date());
        c.add(Calendar.YEAR, -1);
        Date y = c.getTime();
        String year = format.format(y);
        condition.setOrderStartDate(year);

        condition.setUserRole(Optional.ofNullable(condition.getUserRole()).orElse("kh"));
        if ("wl".equals(condition.getUserRole()))
            condition.setLgsCompanyCd(Optional.ofNullable(xcxOrderMapper.getCompanyCdByPhoneNum(Optional.ofNullable(condition.getPhoneNum()).orElse("no_phone"))).orElse("no_company"));
    }

    @Override
    public List searchList(SearchQuery condition) {
        return xcxOrderMapper.searchList(condition);
    }

    @Transactional
    @Override
    public boolean addSign(Long orderId) {
        //更新订单状态为已签收
        LgsOrder condition = new LgsOrder();
        condition.setId(orderId);
        condition.setLgs_status("7");
        if (orderService.update(condition, new UserDO())) {
            //更新物流记录 客户已签收（微信小程序）
            Map<String, Object> map = Maps.newHashMap();
            map.put("orderId", orderId);
            map.put("context", "客户已签收（微信小程序）");
            map.put("ftime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            if (orderTraceService.saveOrderTrace(Collections.singletonList(map)))
                return true;
        }
        return false;
    }


}
